//
//  HMPictureCollectionView.swift
//  GuoGuo
//
//  Created by 艾小新 on 16/8/9.
//  Copyright © 2016年 xiaoxin. All rights reserved.
//

import UIKit
import SDWebImage


// 每一个item之前的间距
private let itemMargin: CGFloat = 5
// 1. 计算出每一张图片多大
private let itemWH = CGFloat(Int(SCREENW - 2 * HMStatusCellMargin - 2 * itemMargin)/3)

class HMPictureCollectionView: UICollectionView {

    let PictureCellRegister = "PictureCellRegister"
    
    var pictData: [HMPictureInfo]? {
        
        didSet {
             label.text = "\(pictData?.count ?? 0)"
            
            // 约束自己
            self.snp_updateConstraints { (make) in
                
                make.size.equalTo(sizeWithCount(pictData?.count ?? 0))
            }
            
               self.reloadData()
        }
        
     
        
    }
   
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()

        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor.whiteColor()
    
        addSubview(label)
        
        label.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
        
        // 自己成为自己的数据源
        self.dataSource = self
        
        // 注册
        registerClass(HMCollectionViewCell.self, forCellWithReuseIdentifier: PictureCellRegister)
        
        // layout
        let layOut = collectionViewLayout as! UICollectionViewFlowLayout
        
        layOut.itemSize = CGSize(width: itemWH, height: itemWH)
        
        layOut.minimumLineSpacing = itemMargin
        
        layOut.minimumInteritemSpacing = itemMargin
    }
    
    /// 根据图片的张数,计算当前控件的大小
    ///
    /// - parameter count: 图片的张数
    ///
    /// - returns: 控件的大小
    private func sizeWithCount(count: Int) -> CGSize {
        
        if count == 1 {
            
            // 读取
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(pictData?.first?.thumbnail_pic) {
            
            var size = image.size
            
            // 如果 size 的宽度低于80.那把就把宽度调整到80,并且高度等比例拉伸
            // 过窄
            if size.width < 80 {
                size.height = 80 / size.width * size.height
                size.width = 80
            }
            

            // 设置itemSize的大小
            // 设置条目的大小
            let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = size
            // 2. 返回该图片的大小
            return size

        }
            
        }

        
        // 设置条目的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        // 2. 计算出有多少列和多少行
        let col = count == 4 ? 2 : (count > 3 ? 3 : count)
        let row = (count - 1) / 3 + 1
        
        // 3. 根据列数和行数,计算整个配图视图的大小
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
        
        return CGSize(width: width, height: height)
    }
    
    
    // MARK: -懒加载
    private lazy var label: UILabel = UILabel(title: "", color: UIColor.darkGrayColor())

    
}



// collectionView的数据源方法
extension HMPictureCollectionView: UICollectionViewDataSource {
    
    // 有多少个item
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictData?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellRegister, forIndexPath: indexPath) as! HMCollectionViewCell
        cell.imgData = pictData![indexPath.item]
        return cell
        
    }
    
}


/*------------------------------------在这里直接写一个cell类------------------------------------*/

class HMCollectionViewCell: UICollectionViewCell {
    
    
    var imgData: HMPictureInfo? {
        
        didSet {
            
            guard let urlString = imgData?.thumbnail_pic else {
                return
            }
            // 显示数据
            imageView.sd_setImageWithURL(NSURL(string: urlString), placeholderImage: UIImage(named: "timeline_image_placeholder"))
        
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        // 加载控件 设置约束
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(contentView)
        }
        
        
    }
    
    
    // MARK: -懒加载
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        // 设置imageView的内容模式
        imageView.contentMode = .ScaleAspectFill
        // 把超出控件的内容给删掉
        imageView.clipsToBounds = true
        return imageView
    }()
    
    
}
